const {
  getHorizontalImageUrlJson,
  getVerticalImageUrlJson,
} = require("./index");

// HTML 模板函数
const htmlTemplate = () => `
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="referrer" content="no-referrer" />
    <title>API</title>
    <!-- <link rel="stylesheet" href="/css/imageApi.css" /> -->
    <link
        rel="stylesheet"
        href="https://gitee.com/li-jiazhen0623/some-file/raw/master/imageApi.css"
      />
  </head>
  <body>
    <div id="loading-indicator" class="loading-indicator">
      <div class="spinner"></div>
      <p>正在加载...</p>
    </div>
    <!-- <script referrerpolicy="no-referrer" src="/js/imageApi.js"></script> -->
    <script
        referrerpolicy="no-referrer"
        src="https://gitee.com/li-jiazhen0623/some-file/raw/master/imageApi.js"
      ></script>
  </body>
</html>
`;

// 公共处理函数
async function handleApiRequest(endpoint, res) {
  try {
    const mockReq = {};
    const mockRes = {
      json: (data) => {
        if (data?.url) {
          return res.redirect(302, data.url);
        }
        throw new Error("Invalid response data");
      },
      status: (code) => ({
        send: (msg) => res.status(code).send(msg),
      }),
    };

    // 根据endpoint调用对应的处理函数
    switch (endpoint) {
      case "verticalJson":
        return getVerticalImageUrlJson(mockReq, mockRes);
      case "horizontalJson":
        return getHorizontalImageUrlJson(mockReq, mockRes);
      default:
        throw new Error("Invalid endpoint");
    }
  } catch (error) {
    console.error("API request failed:", error);
    return res.status(500).send("Failed to fetch data");
  }
}

// 处理垂直壁纸请求
const handleVerticalRequest = (req, res) => {
  const isPageRequest = (req) => {
    const acceptHeader = req.get("Accept") || "";
    return (
      acceptHeader.includes("text/html") &&
      !acceptHeader.includes("text/html;q=0")
    );
  };
  if (isPageRequest(req)) {
    return res.send(htmlTemplate());
  }
  return handleApiRequest("verticalJson", res);
};

// 处理水平壁纸请求
const handleHorizontalRequest = (req, res) => {
  const isPageRequest = (req) => {
    const acceptHeader = req.get("Accept") || "";
    return (
      acceptHeader.includes("text/html") &&
      !acceptHeader.includes("text/html;q=0")
    );
  };
  if (isPageRequest(req)) {
    return res.send(htmlTemplate());
  }
  return handleApiRequest("horizontalJson", res);
};

// 处理自适应壁纸请求
const handleAdaptiveRequest = (req, res) => {
  const isPageRequest = (req) => {
    const acceptHeader = req.get("Accept") || "";
    return (
      acceptHeader.includes("text/html") &&
      !acceptHeader.includes("text/html;q=0")
    );
  };
  if (isPageRequest(req)) {
    return res.send(htmlTemplate());
  }

  const userAgent = req.headers["user-agent"] || "";
  const isMobile = /Mobile|Android|iPhone|BlackBerry|IEMobile|Opera Mini/i.test(
    userAgent
  );
  const isTablet = /iPad|Tablet|Kindle/i.test(userAgent);

  const endpoint = isMobile && !isTablet ? "verticalJson" : "horizontalJson";
  return handleApiRequest(endpoint, res);
};

module.exports = {
  handleVerticalRequest,
  handleHorizontalRequest,
  handleAdaptiveRequest,
};
